<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form v-show="showSearch" ref="queryRef" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="请输入手机号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="queryParams.email" placeholder="请输入邮箱" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 按钮组 -->
    <el-row v-if="$store.getters.role == 0" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
    </el-row>

    <!-- 用户表格 -->
    <el-table v-loading="loading" :data="userList" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column v-if="$store.getters.role == 0" type="selection" width="55" align="center" />
      <el-table-column label="用户ID" align="center" prop="id" />
      <el-table-column label="用户名" align="center" prop="username" />
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="邮箱" align="center" prop="email" />
      <el-table-column label="角色" align="center" prop="role">
        <template #default="{ row }">
          <el-tag :type="row.role == 0 ? 'success' : 'info'" size="small">
            {{ row.role == 0 ? '管理员' : '普通用户' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="最后登录时间" align="center" prop="lastLoginTime">
        <template #default="{ row }">
          {{ row.lastLoginTime || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" />
      <!-- 表格行内操作 -->
      <el-table-column v-if="$store.getters.role == 0" label="操作" align="center" width="150">
        <template v-slot="scope">
          <div class="action-buttons">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>

    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-show="total > 0"
      :current-page.sync="queryParams.pageNum"
      :page-size.sync="queryParams.pageSize"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @current-change="getList"
      @size-change="handleSizeChange"
    />

    <!-- 添加/修改用户弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="userRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" :placeholder="form.id ? '留空则不修改密码' : '请输入密码'" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="管理员" :value="0" />
            <el-option label="普通用户" :value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser } from '@/api/userGL/user'

export default {
  name: 'UserGL',
  data() {
    return {
      userList: [],
      open: false,
      loading: false,
      showSearch: true,
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      title: '',
      form: {},
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        username: '',
        phone: '',
        email: '',
        password: '',
        passwordSetTime: '',
        status: ''
      },
      rules: {
        username: [{ required: true, message: '用户名必须是4-20位的字母、数字或下划线', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入有效的手机号码', trigger: 'blur' }],
        email: [{ required: true, message: '请输入有效的邮箱地址', trigger: 'blur' }],
        password: [{ 
          required: false, 
          message: '密码必须包含大小写字母、数字和特殊符号，且长度至少8位', 
          trigger: 'blur',
          validator: (rule, value, callback) => {
            // 新增用户时密码必填
            if (!this.form.id && !value) {
              callback(new Error('新增用户时密码不能为空'));
            }
            // 修改用户时密码可选，但如果填写了则必须符合格式
            else if (this.form.id && value && value.length < 8) {
              callback(new Error('密码长度至少8位'));
            }
            else {
              callback();
            }
          }
        }],
        role: [{ required: true, message: '请选择用户角色', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      this.loading = true
      const params = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        username: this.queryParams.username,
        phone: this.queryParams.phone,
        email: this.queryParams.email
      }
      try {
        const res = await listUser(params) // 等待请求完成
        console.log('getList res:', res)
        if (res && res.code === 200 && res.data) {
          this.userList = (res.data.rows || []).map(item => ({ ...item }))
          this.total = res.data.total || 0
        } else {
          // 使用你项目的提示方法（这里兼容 $modal / $message）
          (this.$modal?.msgError || this.$message?.error || console.error)(res?.msg || '查询失败')
        }
        return res
      } catch (err) {
        console.error('getList error:', err);
        (this.$modal?.msgError || this.$message?.error || console.error)('查询异常')
        throw err
      } finally {
        this.loading = false
      }
    },

    handleSizeChange(size) {
      this.queryParams.pageSize = size
      this.getList()
    },
    cancel() {
      this.open = false
      this.reset()
    },
    reset() {
      this.form = {
        id: null,
        username: null,
        phone: null,
        email: null,
        password: null,
        role: 1, // 默认为普通用户
        passwordSetTime: null,
        createTime: null,
        updateTime: null,
        lastLoginTime: null,
        status: null
      }
      this.$refs.userRef && this.$refs.userRef.resetFields()
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.$refs.queryRef && this.$refs.queryRef.resetFields()
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id).filter(id => id !== undefined)
      this.single = selection.length !== 1
      this.multiple = selection.length === 0
    },

    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加用户管理'
    },
    handleUpdate(row) {
      this.reset()
      const _id = row ? row.id : this.ids[0]
      if (!_id) {
        this.$modal.msgError('请先选择用户')
        return
      }
      getUser(_id).then(res => {
        if (res && res.code === 200 && res.data) {
          // 携带用户原来的信息，但清空密码字段
          this.form = {
            ...res.data,
            password: '' // 修改时不显示原密码
          }
          this.open = true
          this.title = '修改用户管理'
        } else {
          this.$modal.msgError(res.msg || '获取用户信息失败')
        }
      }).catch(err => {
        console.error(err)
        this.$modal.msgError('请求异常')
      })
    },
    async submitForm() {
      // 把 validate 用 Promise 包起来，便于 await
      const valid = await new Promise(resolve => {
        this.$refs.userRef.validate(valid => resolve(valid))
      })
      if (!valid) return

      this.loading = true
      try {
        if (this.form.id != null) {
          // 修改用户
          const updateData = { ...this.form }
          // 如果密码为空，则不传递密码字段
          if (!updateData.password) {
            delete updateData.password
          }
          const res = await updateUser(updateData.id, updateData)
          console.log('updateUser res:', res)
          if (res && res.code === 200) {
            (this.$modal?.msgSuccess || this.$message?.success)('修改成功')
            // 先刷新数据再关 dialog（保证 UI 能看到最新数据）
            await this.getList()
            this.open = false
          } else {
            (this.$modal?.msgError || this.$message?.error)(res?.msg || '修改失败')
            return
          }
        } else {
          // 新增用户
          const res = await addUser(this.form)
          console.log('addUser res:', res)
          if (res && res.code === 200) {
            (this.$modal?.msgSuccess || this.$message?.success)('新增成功')
            await this.getList()
            this.open = false
          } else {
            (this.$modal?.msgError || this.$message?.error)(res?.msg || '新增失败')
            return
          }
        }
      } catch (err) {
        console.error('submitForm error:', err);
        (this.$modal?.msgError || this.$message?.error)('提交异常')
      } finally {
        this.loading = false
      }
    },

    async handleDelete(row) {
      const _ids = row ? [row.id] : this.ids.filter(id => id !== undefined)

      if (!_ids.length) return this.$message.error('请选择要删除的用户')

      this.$confirm(`是否确认删除选中的 ${_ids.length} 条用户数据？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        delUser(_ids).then(res => {
          if (res && res.code === 200) {
            this.$message.success('删除成功')
            this.getList() // ✅ 删除后刷新列表
            this.ids = []
          } else {
            this.$message.error(res?.msg || '删除失败')
          }
          // eslint-disable-next-line no-return-assign
        }).finally(() => this.loading = false)
      }).catch(() => {})
    },

    handleExport() {
      this.$download('userGL/user/export', { ...this.queryParams }, `user_${Date.now()}.xlsx`)
    }
  }
}
</script>

<style scoped>
.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
}
</style>
